package com.gxgeek.javabasic.nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author gaoxing
 * @create 2018-06-06 下午8:46
 */
public class IOvsNIOTest {

    public static void main(String[] args) {
        method1();
//        method2();

    }
    public static String path = "/Users/gaoxing/Desktop/code/study/javastudy/testfilechannel.txt";
    public static void method1()  {



//        RandomAccessFile aFile = null;
        try{
            Path path = Paths.get(IOvsNIOTest.path);
            FileChannel fileChannel = FileChannel.open(path);
//            aFile = new RandomAccessFile(path,"rw");
//            FileChannel fileChannel = aFile.getChannel();
            ByteBuffer buf = ByteBuffer.allocate(1024);

            int bytesRead = fileChannel.read(buf);
            System.out.println(bytesRead);

            while(bytesRead != -1)
            {
                buf.flip();
                while(buf.hasRemaining())
                {
//                    System.out.print((char)buf.get());
//                    String value = new String(((byte)buf.get()),"utf-8");
                    System.out.print(Charset.forName("utf-8").decode(buf));  // 这样读取，如果10字节恰好分割了一个字符将出现乱码

                }

//                buf.clear();// 清空,position位置为0，limit=capacity
                buf.compact();
                //  继续往buffer中写
                bytesRead = fileChannel.read(buf);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally{
//            try{
//
//                if(aFile != null){
//                    aFile.close();
//                }
//            }catch (IOException e){
//                e.printStackTrace();
//            }
        }
    }

    public static void method2() {
        InputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(path));

            byte[] buf = new byte[1024];
            int bytesRead = in.read(buf);
            while (bytesRead != -1) {
                for (int i = 0; i < bytesRead; i++)
                    System.out.print((char) buf[i]);
                bytesRead = in.read(buf);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
